package main

import (
	"fmt"

	"gitee.com/woodpile/wgs.ths.code.generate/definition"
	config "gitee.com/woodpile/wgs.ths.config.go"
	"github.com/urfave/cli/v3"
)

func init() {
	definition.GlobalConfig.Cmd = &Config{}

	config.GlobalRendererFlag.BindFlag("verbose", "", "verbose")
}

type Config struct {
	PlaceHolder string `yaml:"place_holder,omitempty"`
}

func (*Config) Name() string {
	return "cmd"
}

func (*Config) ToDefault(cfg config.IConfigDefault) {
	ac := cfg.(*Config)
	ac.PlaceHolder = "default_place_holder"
}

func loadConfig(cmd *cli.Command) error {
	setFlagLookupFunc(cmd)
	configFilepath := cmd.String("config")

	config.GlobalRendererFile.ConfigFilepaths([]string{
		configFilepath,
	})
	if err := config.DefaultContext.RenderConfig(); err != nil {
		return err
	}
	return nil
}

// 设置配置解析的flag查找函数
func setFlagLookupFunc(cmd *cli.Command) {
	config.GlobalRendererFlag.SetLookupFunc(func(cmdPath, flagName string) (string, bool) {
		//1. 根据cmdPath选中第几级cli.Context
		currentCmdPath := ""
		var foundCtx *cli.Command
		lineage := cmd.Lineage()
		for i := len(lineage) - 1; i >= 0; i-- {
			c := lineage[i]
			if c == nil {
				continue
			}
			if c.Name == "wgs_code_generate" {
				if cmdPath == "wgs_code_generate" || cmdPath == "" {
					foundCtx = c
					break
				}
				continue
			}
			currentCmdPath += "." + c.Name
			if currentCmdPath == cmdPath {
				foundCtx = c
				break
			}
		}
		if foundCtx == nil {
			//没有找到对应的cli.Context
			return "", false
		}

		//2. 根据flagName选中flag
		if !foundCtx.IsSet(flagName) {
			return "", false
		}
		fv := fmt.Sprintf("%v", foundCtx.Value(flagName))
		return fv, true
	})
}

func scriptModifyConfig(ctx *definition.Context) error {
	for _, f := range ctx.FuncConfigModify {
		if err := f(definition.GlobalConfig); err != nil {
			return fmt.Errorf("script modify config error: %w", err)
		}
	}
	return nil
}
